﻿//
// Copyright (C) Canyala Innovation AB 2011
//

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Text;

using Canyala.Lagoon.Extensions;

namespace Canyala.Lagoon.Presentation
{
    public class PropertyManager : DynamicObject
    {
        private readonly ViewModel _viewModel;
        private readonly Dictionary<string, object> _properties = new Dictionary<string, object>();

        internal PropertyManager(ViewModel viewModel) 
            { _viewModel = viewModel; }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (_properties.ContainsKey(binder.Name))
                _properties.Remove(binder.Name);

            _properties.Add(binder.Name, value);
            _viewModel.NotifyChanged(binder.Name);

            PropagateNotifyChanged(_viewModel, binder.Name);

            return true;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_properties.TryGetValue(binder.Name, out result))
                return true;

            return false;
        }

        private static void PropagateNotifyChanged(ViewModel viewModel, string propertyPath)
        {
            var modelType = viewModel.GetType();

            foreach (var property in modelType.GetProperties())
            {
                foreach (var dependencyAttribute in property.GetCustomAttributes<DependsOnAttribute>())
                {
                    if (dependencyAttribute.HasDependencyOn(propertyPath))
                        viewModel.NotifyChanged(property.Name);

                    if (viewModel.Parent != null)
                        viewModel
                            .Parent
                            .GetType()
                            .GetProperties()
                            .Where(p => p.PropertyType == modelType)
                            .Do(parentProperty => PropagateNotifyChanged(viewModel.Parent, "{0}.{1}".Args(parentProperty.Name, propertyPath)));
                }
            }
        }
    }
}
